package fzw.jsmx.aptlib_processor

import fzw.jsmx.aptlib_anno.InitActivity
import fzw.jsmx.aptlib_anno.InitModel
import javax.annotation.processing.AbstractProcessor
import javax.annotation.processing.RoundEnvironment
import javax.lang.model.element.TypeElement

class AndroidProcess : AbstractProcessor() {

    override fun getSupportedAnnotationTypes(): Set<String> {
        return setOf(InitModel::class.java.canonicalName)
    }

    override fun process(annotations: Set<TypeElement?>, roundEnv: RoundEnvironment): Boolean {
        roundEnv.getElementsAnnotatedWith(InitActivity::class.java)
            ?.filterNotNull()
            ?.forEach {
                val cla = it.enclosingElement.toString()
                val annotation = it.getAnnotation(InitActivity::class.java)
                val simple = annotation.name + "Activity"
                val file =
                    processingEnv.filer.createSourceFile("$cla.$simple", it)
                file.openWriter()
                    .run {
                        write(ProcessUtil.createActivity(cla, simple, annotation))
                        flush()
                        close()
                    }
            }
        roundEnv.getElementsAnnotatedWith(InitModel::class.java)
            ?.filterNotNull()
            ?.forEach {
                val cla = it.enclosingElement.toString()
                val annotation = it.getAnnotation(InitModel::class.java)
                val simple = it.simpleName.toString() + "Model"
                val file =
                    processingEnv.filer.createSourceFile("$cla.$simple", it)
                file.openWriter()
                    .run {
                        write(ProcessUtil.createModel(cla, simple, annotation))
                        flush()
                        close()
                    }
            }
        return false
    }

}